package com.jn.rxjava.views;

import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jn.rx_java_demo.R;
import com.jn.rxjava.Client.RetrofitClient_today;
import com.jn.rxjava.adapter.ImageAdapter;
import com.jn.rxjava.service.ImageApiService;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class BingImageActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ImageAdapter adapter;
    private CompositeDisposable compositeDisposable = new CompositeDisposable();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.image_activity);
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ImageAdapter((FragmentActivity) this);
        recyclerView.setAdapter(adapter);

        loadImages();

    }

    private void loadImages() {
        compositeDisposable.add(
                RetrofitClient_today.getClient().create(ImageApiService.class)
                        .getBingImages()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(bingResponse -> {
                            if (bingResponse.getCode() == 200) {
                                adapter.setImages(bingResponse.getResult());
                            } else {
                                Toast.makeText(BingImageActivity.this, "Failed to load images", Toast.LENGTH_SHORT).show();
                            }
                        }, throwable -> {
                            Toast.makeText(BingImageActivity.this, "Error: " + throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        })
        );
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.clear();
    }
}